from models import article
from app.app_init import db
from sqlalchemy import Select, Update, func


class ArticleService:

    def get_article(self, id):
        return db.session.get(article.Article, id)


    def get_articles(self):
        query = Select(article.Article)
        return db.session.scalars(query).all()

    def create_article(self, article: article.Article):
        db.session.add(article)
        db.session.commit()
        return article

    def update_article(self, article: article.Article):
        old_article = self.get_article(article.id)
        old_article.title = article.title
        old_article.content = article.content
        old_article.update_time = func.now()
        db.session.commit()
        return old_article

    def delete_article(self, article_id):
        article = self.get_article(article_id)
        if article:
            res = db.session.delete(article)
            db.session.commit()
            return True
        return False

